package com.note.user.config;

import com.note.config.constants.constants.GlobalConstants;
import com.note.user.vo.ResponseVo;
import jakarta.validation.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Package：com.note.user.config
 * @Name：GlobalExceptionHandler
 * @Author：热伊木
 * @Email：uyevan@163.com
 * @Date：2023-12-12-9:06
 * @Description：全局统一异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 全局异常捕获 运行时异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseVo exceptionHandler(Exception e) {
        log.error("捕获到Exception异常！{}", e);
        String message = e.getMessage();
        int index = message.indexOf(":");
        if (index > 0) {
            message = message.substring(index + 1).trim();
        }
        return new ResponseVo(GlobalConstants.ERROR, false, message);
    }

    /**
     * 全局Controller上校验参数异常捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ValidationException.class)
    public ResponseVo constraintViolationException(ValidationException e) {
        log.error("捕获到ValidationException异常！{}", e);
        String message = e.getMessage();
        int index = message.indexOf(":");
        if (index > 0) {
            message = message.substring(index + 1).trim();
        }
        /*多个参数只返回第一个*/
        String[] errorMessage = message.split(",");
        return new ResponseVo(GlobalConstants.ERROR, false, errorMessage[0]);
    }

    /**
     * 全局校验参数异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(BindException.class)
    public ResponseVo<Void> bindExceptionHandler(BindException e) {
        log.error("捕获到BindException异常！{}", e);
        return new ResponseVo(GlobalConstants.BAD_REQUEST, false, e.getBindingResult().getAllErrors().get(0).getDefaultMessage());
    }
}
